﻿using EasyCore.Extensions;
using EasyCore.ObjectMapper.Attributes;
using EasyCore.Reflection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EasyCore.ObjectMapper
{
    /// <summary>
    /// 创建源类型与目标类型的配对
    /// </summary>
    public class MapFromAndMapToProfile : AutoMapperTupleBase
    {    

        public MapFromAndMapToProfile() 
        {
            List<(Type Source, Type Target)> tuples = new List<(Type Source, Type Target)>();
            Type[] types = AssemblyManager.FindTypesByAttribute<MapFromAttribute>();
            foreach (Type targetType in types)
            {
                MapFromAttribute attribute = targetType.GetAttribute<MapFromAttribute>(true);
                foreach (Type sourceType in attribute.SourceTypes)
                {
                    var tuple = ValueTuple.Create(sourceType, targetType);
                    tuples.AddIfNotExist(tuple);
                }
            }
            types = AssemblyManager.FindTypesByAttribute<MapToAttribute>();
            foreach (Type sourceType in types)
            {
                MapToAttribute attribute = sourceType.GetAttribute<MapToAttribute>(true);
                foreach (Type targetType in attribute.TargetTypes)
                {
                    var tuple = ValueTuple.Create(sourceType, targetType);
                    tuples.AddIfNotExist(tuple);
                }
            }
            types = AssemblyManager.FindTypesByAttribute<MapAttribute>();
            foreach (Type sourceType in types)
            {
                MapAttribute attribute = sourceType.GetAttribute<MapAttribute>(true);
                foreach (Type targetType in attribute.Types)
                {
                    var tuple = ValueTuple.Create(sourceType, targetType);
                    tuples.AddIfNotExist(tuple);
                    tuple = ValueTuple.Create(targetType, sourceType);
                    tuples.AddIfNotExist(tuple);
                }
            }

            foreach ((Type Source, Type Target) tuple in tuples)
            {
                CreateMap(tuple.Source, tuple.Target);          
            }
        }

       
        /// <summary>
        /// 获取 排序
        /// </summary>
        public override int Order => -9999;   
    }
}
